package cn.datax.service.data.metadata.console.controller;

import cn.afterturn.easypoi.entity.vo.NormalExcelConstants;
import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
import cn.afterturn.easypoi.excel.entity.params.ExcelExportEntity;
import cn.afterturn.easypoi.view.PoiBaseView;
import cn.datax.commo.office.excel.ExcelUtils;
import cn.datax.common.base.BaseController;
import cn.datax.common.core.R;
import cn.datax.common.validate.ValidationGroups;
import cn.datax.service.data.metadata.api.dto.SqlConsoleDto;
import cn.datax.service.data.metadata.api.vo.SqlConsoleVo;
import cn.datax.service.data.metadata.console.service.SqlConsoleService;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.util.ListUtils;
import com.alibaba.excel.write.builder.ExcelWriterBuilder;
import com.alibaba.excel.write.handler.WriteHandler;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.LambdaUtils;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/sql")
public class SqlConsoleController extends BaseController {

    @Autowired
    private SqlConsoleService sqlConsoleService;

    @PostMapping("/run")
    public R sqlRun(@RequestBody @Validated SqlConsoleDto sqlConsoleDto){
        List<SqlConsoleVo> list = sqlConsoleService.sqlRun(sqlConsoleDto);
        return R.ok().setData(list);
    }

    @PostMapping("/download")
    public void sqlDataDownload(@RequestBody @Validated SqlConsoleDto sqlConsoleDto, HttpServletRequest request, HttpServletResponse response){
        List<SqlConsoleVo> list = sqlConsoleService.sqlRun(sqlConsoleDto);


        String fileName =  "dynamicHeadWrite" + System.currentTimeMillis() + ".xlsx";



                response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        try {
            response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode(fileName, "utf-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        ServletOutputStream outputStream = null;
        try {
            outputStream = response.getOutputStream();
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 定义动态表头样式
        CellStyle headerCellStyle = createHeaderCellStyle();

        // 写入表头数据
        EasyExcel.write(outputStream)
                .autoCloseStream(true)
                // 这里放入动态头
                .head(head(list.get(0).getColumnList())).sheet("模板")
                // 当然这里数据也可以用 List<List<String>> 去传入
                .doWrite(data(list.get(0).getDataList()));

    }

    @PostMapping("/stop")
    public R sqlStop(@RequestBody @Validated({ValidationGroups.Other.class}) SqlConsoleDto sqlConsoleDto){
        sqlConsoleService.sqlStop(sqlConsoleDto);
        return R.ok();
    }
    private List<List<String>> data( List<Map<String, Object>> inData) {
        List<List<String>> list = ListUtils.newArrayList();
        for (int i = 0; i < inData.size(); i++) {
            List<String> temp = ListUtils.newArrayList();
            inData.get(i).forEach((key, value) -> {
                temp.add(value == null ? "" : value.toString());
            });
            list.add(temp);
        }
        return list;
    }
    private CellStyle createHeaderCellStyle() {
        Workbook workbook = new XSSFWorkbook();
        Sheet sheet = workbook.createSheet("Sheet1");
        CellStyle cellStyle = workbook.createCellStyle();
        Font font = workbook.createFont();
        font.setBold(true);
        cellStyle.setFont(font);
        return cellStyle;
    }


    private List<List<String>> head( List<String> inList) {
        List<List<String>> list = new ArrayList<List<String>>();
        for (int i = 0; i < inList.size(); i++) {
            List<String> temp = new ArrayList<String>();
            temp.add(inList.get(i));
            list.add(temp);
        }
        return list;
    }
}
